package com.xhwh.wx.controller;

import com.xhwh.wx.service.CoreService;
import com.xhwh.wx.util.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;



/**
 * Created by Administrator on 2015/3/17.
 */

@Controller
public class EnterpriseCoreController {

    @RequestMapping(value = { "/enterpriseCoreJoin.do" }, method = RequestMethod.GET)
    public void coreJoinGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String msg_signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        String result = null;
        if (SignUtil.checkSignature(msg_signature, timestamp, nonce)) {
            result = echostr;
        }

        if (result == null) {
            result = "Error！";
        }

        out.print(result);
        out.close();
        out = null;
    }

    @RequestMapping(value = { "/enterpriseCoreJoin.do" }, method = RequestMethod.POST)
    public void coreJoinPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 微信加密签名
        String msg_signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        PrintWriter out = response.getWriter();
        // 请求校验

        if(SignUtil.checkSignature(msg_signature, timestamp, nonce)) {
            // 调用核心服务类接收处理请求
            String respXml = CoreService.processRequest(request);
            out.print(respXml);
        }

        out.close();
        out = null;

    }
}
